package artid.com.arttogoa;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

import artid.com.arttogoa.R;

import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.AppItem;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：ForgetPasswordActivity   
 * 类描述：忘记密码   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:20:32      
 *
 */
public class ForgetPasswordActivity extends BaseActivity implements
OnClickListener {
	private Button mFindLogin, mForgetGetCode;
	private MyEditText phone, code, password;
	private CheckBox eyeBtn;
	private IntentFilter mIntentFilter;
	private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
	private String strContent;
	private Handler mHandler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				code.setText(strContent);
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forget_password);
		setContent(this, getIntent());
		setBack();
		initView();
	}

	private void initView() {
		mContext = this;
		ArtWorkApp.getInstance().addActivity(this);
		mFindLogin = (Button) findViewById(R.id.find_login);
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("忘记密码");
		setBack();
		mForgetGetCode = (Button) findViewById(R.id.forget_get_code);
		phone = (MyEditText) findViewById(R.id.forget_phone);
		phone.setText(MySharedPreferences.getMySharedPreferences(mContext).getValue("Phone", ""));
		code = (MyEditText) findViewById(R.id.forget_code);
		password = (MyEditText) findViewById(R.id.forget_password);
		phone.addTextChangedListener(mTextChangedListener);
		code.addTextChangedListener(mTextChangedListener);
		password.addTextChangedListener(mTextChangedListener);
		eyeBtn = (CheckBox) findViewById(R.id.forget_pass_visible);
		mForgetGetCode.setOnClickListener(this);
		mBack.setOnClickListener(this);
		mFindLogin.setOnClickListener(this);
		eyeBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					// 如果选中，显示密码
					password.setTransformationMethod(HideReturnsTransformationMethod
							.getInstance());
				} else {
					// 否则隐藏密码
					password.setTransformationMethod(PasswordTransformationMethod
							.getInstance());
				}

			}
		});
		conditionJudge();
		//注册短信监听
		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		mIntentFilter.setPriority(Integer.MAX_VALUE);
		registerReceiver(broadcastReceiver, mIntentFilter);
		registerUmPush();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.forget_get_code:
			//获取验证码
			getCode();
			break;
		case R.id.find_login:
			//修改操作
			if(StringUtils.isEmpty(PushAgent.getInstance(mContext).getRegistrationId())){
				showToast("修改失败，请重新修改");
				return;
			}
			findPass();
			// Intent in = new Intent(ForgetPasswordActivity.this,
			// MainActivity.class);
			// startActivity(in);
			// finish();
			break;

		default:
			break;
		}

	}

	/**
	 * 条件判断
	 */
	private void conditionJudge(){
		if(!StringUtils.isEmpty(phone.getText().toString()) && !StringUtils.isEmpty(password.getText().toString()) && 
				!StringUtils.isEmpty(code.getText().toString()) && RegexUtil.isMobile(phone.getText().toString())){
			mFindLogin.setEnabled(true);
			mFindLogin.setBackgroundResource(R.drawable.red_frame);
		}else{
			mFindLogin.setEnabled(false);
			mFindLogin.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   

			//对按钮的判断是否可用
			conditionJudge();
		}  
	};  

	/**
	 * 修改密码网络请求
	 */
	private void findPass() {
		VolleyBasic.getInstance(ForgetPasswordActivity.this).post(true,false, Cache.resetPwdData,
				VolleyMap.getInstance().resetPwd(password.getText().toString(),
						code.getText().toString(), phone.getText().toString()),
						AppItem.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						login();
					}

					@Override
					public void onError(VolleyError volleyError) {

					}
				});
	}

	/**
	 * 获取验证码
	 */
	private void getCode() {
		if (TextUtils.isEmpty(phone.getText().toString())) {
			Toast.makeText(mContext, "手机号不能为空~", 2).show();
			return;
		} else if (!RegexUtil.isMobile(phone.getText().toString())) {
			Toast.makeText(mContext, "手机号格式不正确，请重新输入~", 2).show();
			return;
		}
		VolleyBasic.getInstance(ForgetPasswordActivity.this).post(
				Cache.sendresetcode,
				VolleyMap.getInstance().sendresetcode(
						phone.getText().toString()), AppItem.class,
						new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						timer.start();
					}

					@Override
					public void onError(VolleyError volleyError) {

					}
				});

	}

	private void registerUmPush(){
		//当推送token获取不到的时候重新注册一下
		if(StringUtils.isEmpty(PushAgent.getInstance(mContext).getRegistrationId())){
			// 友盟注册
			//注册推送服务，每次调用register方法都会回调该接口
			PushAgent.getInstance(this).register(new IUmengRegisterCallback() {

				@Override
				public void onSuccess(String deviceToken) {
					//注册成功会返回device token
					Log.d("log", "友盟ID：" + deviceToken);
				}

				@Override
				public void onFailure(String s, String s1) {
					Log.d("log", "初始化友盟错误：" + s.toString() + "===" + s1.toString());
				}
			});
		}
	}

	/**
	 * 登录
	 */
	private void login() {
		VolleyBasic.getInstance(this).post(
				Cache.login,
				VolleyMap.getInstance().Login(phone.getText().toString(),
						password.getText().toString(),PushAgent.getInstance(this).getRegistrationId()), UserItem.class,
						new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						try {
							// TODO Auto-generated method stub
							System.out.println(vd.getJson());
							UserItem us = (UserItem) vd.getData();
							DataKeeper.keepSerializable(ForgetPasswordActivity.this, us);
							AppUtil.setUser();
							MySharedPreferences.getMySharedPreferences(mContext).setValue("Phone", phone.getText().toString());
							MySharedPreferences.getMySharedPreferences(mContext).setValue("PassWord", password.getText().toString());
							Intent in = new Intent(ForgetPasswordActivity.this,MainActivity.class);
							startActivity(in);
							ArtWorkApp.getInstance().exit();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					public void onError(VolleyError volleyError) {

					}
				});

	}



	private CountDownTimer timer = new CountDownTimer(60000, 1000) {

		@Override
		public void onTick(long millisUntilFinished) {
			mForgetGetCode.setText((millisUntilFinished / 1000) + "秒后可重发");
			mForgetGetCode.setClickable(false);
		}

		@Override
		public void onFinish() {
			mForgetGetCode.setEnabled(true);
			mForgetGetCode.setClickable(true);
			mForgetGetCode.setText("获取验证码");
		}
	};

	/**
	 * 匹配短信中间的6个数字（验证码等）
	 * 
	 * @param patternContent
	 * @return
	 */
	private String patternCode(String patternContent) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	/**
	 * 广播
	 */
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Object[] objs = (Object[]) intent.getExtras().get("pdus");
			for (Object obj : objs) {
				byte[] pdu = (byte[]) obj;
				SmsMessage sms = SmsMessage.createFromPdu(pdu);
				// 短信的内容
				String message = sms.getMessageBody();
				Log.d("log", "message     " + message);
				// 短息的手机号。。+86开头？
				String from = sms.getOriginatingAddress();
				Log.d("log", "from     " + from);
				if (!TextUtils.isEmpty(from)) {
					String code = patternCode(message);
					if (!TextUtils.isEmpty(code)) {
						strContent = code;
						mHandler.sendEmptyMessage(1);
					}
				}
			}
		}
	};

	protected void onDestroy() {
		super.onDestroy();
		//关闭广播
		unregisterReceiver(broadcastReceiver);
	};
}
